package com.nwpu.coursesupport.service.imple;

import com.nwpu.coursesupport.entity.CourseTarget;
import com.nwpu.coursesupport.entity.EvaluationOfCourseTargetEntity;
import com.nwpu.coursesupport.entity.bean.Response;
import com.nwpu.coursesupport.mapper.CourseTargetDao;
import com.nwpu.coursesupport.mapper.EvaluationOfCourseTargetDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseTargetService {
    @Autowired
    private CourseTargetDao courseTargetDao;
    @Autowired
    private EvaluationOfCourseTargetDao evaluationOfCourseTargetDao;

    public Response findAll() {
        List<CourseTarget> courseTargets = courseTargetDao.findAll();
        return Response.ok(courseTargets);
    }

    public Response submitCourseTarget(Integer courseId,
                                       List<CourseTarget> courseTargets,
                                       List<EvaluationOfCourseTargetEntity> evaluationOfCourseTargets) {
        //删除该课程的课程目标以及评价方式
        //根据courseId删除courseTarget
        //根据courseTarget删除evaluationOfCourseTarget
        List<CourseTarget> courseTargetList = courseTargetDao.findByCourseId(courseId);
        for (CourseTarget courseTarget : courseTargetList) {
            courseTargetDao.deleteById(courseTarget.getId());
            List<EvaluationOfCourseTargetEntity> evaluationOfCourseTargetEntities =
                    evaluationOfCourseTargetDao.findByCourseTargetId(courseTarget.getId());
            for (EvaluationOfCourseTargetEntity evaluationOfCourseTargetEntity : evaluationOfCourseTargetEntities) {
                evaluationOfCourseTargetDao.deleteById(evaluationOfCourseTargetEntity.getId());
            }
        }

        //保存
        float total1 = 0;
        float total2 = 0;
        for(CourseTarget courseTarget : courseTargets){
            total1 += courseTarget.getWeight();
        }
        for(EvaluationOfCourseTargetEntity evaluationOfCourseTargetEntity : evaluationOfCourseTargets){
            total2+= evaluationOfCourseTargetEntity.getWeight();
        }
        if(total1==1&&total2==1){
            for (CourseTarget courseTarget : courseTargets) {

                courseTarget.setCourseId(courseId);
                courseTargetDao.save(courseTarget);
            for (EvaluationOfCourseTargetEntity evaluationOfCourseTargetEntity : evaluationOfCourseTargets) {
                evaluationOfCourseTargetEntity.setCourseTargetId(courseTarget.getId());
                evaluationOfCourseTargetDao.save(evaluationOfCourseTargetEntity);
            }

            }
            return Response.ok(null);
        }
        else {
            return Response.fail("权重和不为1");
        }

    }

    public List<CourseTarget> courseTargetsByCourseId(Integer courseId) {

        return courseTargetDao.findByCourseId(courseId);


        ///
        ///

        //return Response.ok(courseTargetSubmit);
    }
}
